﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

namespace Common
{
    public static class JsonHelper
    {
        public static string ToJson(this DataTable Table)
        {
            if (Table.DataTableHasData() == false)
            {
                return "[]";
            }

            List<string> list = new List<string>();
            foreach (DataRow dr in Table.Rows)
            {
                List<string> listRow = new List<string>();
                foreach (DataColumn dc in Table.Columns)
                {
                    string val = dr[dc].GetString();

                    if (dc.DataType.GetDbType().DbTypeIsNumber())
                    {
                        ;
                    }
                    else if (dc.DataType == typeof(bool))
                    {
                        ;
                    }
                    else
                    {
                        val = @"""" + val + @"""";
                    }

                    listRow.Add(
                        string.Format(@"""{0}"":{1}", dc.ColumnName, val)
                        );
                }

                list.Add("{" + string.Join(",", listRow.ToArray()) + "}");
            }

            return "[" + string.Join(",", list.ToArray()) + "]";
        }

        public static string ToJson(this object source)
        {
            if (source == null) return null;

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            //执行序列化
            return jsonSerializer.Serialize(source);
        }

        /// <summary>
        /// NameValueCollection 反序列化会出错。可以用 Dictionary&lt;string,string> 来代替。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T FromJSon<T>(this string str)
        {
            if (str.HasValue() == false)
            {
                return default(T);
            }
            else
            {
                string ss = str.Trim().Replace(Environment.NewLine, "");
                if (ss.StartsWith("[") == false && ss.StartsWith("{") == false)
                {
                    str = "{" + str + "}";
                }
            }
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            return jsonSerializer.Deserialize<T>(str);
        }



        // 通过JSON序列化深度克隆类型
        public static T DeepClone<T>(this T Source)
        {
            string jsonString = Source.ToJson();
            return jsonString.FromJSon<T>();
        }
    }
}
